package com.qianfeng.xinyihezi.xinyihezi.activity.activity_meng;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.icu.util.Calendar;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ecloud.pulltozoomview.PullToZoomScrollViewEx;
import com.qianfeng.xinyihezi.xinyihezi.R;
import com.qianfeng.xinyihezi.xinyihezi.adapter.adapter_meng.MyListViewAdapter;
import com.qianfeng.xinyihezi.xinyihezi.adapter.adapter_meng.MyRecycleViewAdapter;
import com.qianfeng.xinyihezi.xinyihezi.customview.MyListView;
import com.qianfeng.xinyihezi.xinyihezi.model.bean_meng.Goods;
import com.qianfeng.xinyihezi.xinyihezi.model.bean_meng.User;
import com.qianfeng.xinyihezi.xinyihezi.netinterface.RetrofitInterface;
import com.qianfeng.xinyihezi.xinyihezi.url.NetURL;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class DetailsActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    private Retrofit mRetrofit;
    private RetrofitInterface mInterface;
    private List<User> mList;
    private PullToZoomScrollViewEx scrollView;
    private ProgressDialog mDialog;
    private int avatar_count;
    private MyRecycleViewAdapter mAdapter;
    private GridLayoutManager manager;
    private List<Goods> mListGoodsAll;
    private List<Goods> mListGoods;
    private MyListViewAdapter mAdapterList;
    private TextView mTextViewMore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_details);
        // 注意初始化顺序，不要弄乱，否则抛出运行时空指针
        initData();
    }

    private void initView() {
        scrollView = (PullToZoomScrollViewEx) findViewById(R.id.scroll_view);
        loadViewForPullToZoomScrollView(scrollView);

        scrollView.getPullRootView().findViewById(R.id.tv_test1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("PullToZoomScrollViewEx1", "onClick");
            }
        });

        scrollView.getPullRootView().findViewById(R.id.tv_test3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("PullToZoomScrollViewEx3", "onClick");
            }
        });
        setPullToZoomViewLayoutParams(scrollView);
    }

    private void initData() {
        mListGoods = new ArrayList<>();
        mListGoodsAll = new ArrayList<>();
        mDialog = new ProgressDialog(this);
        mDialog.setMessage("正在加载");
        mDialog.show();
        mList = new ArrayList<>();
        mRetrofit = new Retrofit.Builder()
                // 设置基地址
                .baseUrl(NetURL.HEAD_URL)
                // 设置转换工厂  用于Json解析
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        // 初始化接口实例
        mInterface = mRetrofit.create(RetrofitInterface.class);
        loadUser();
        loadData();
    }

    private void loadData() {
        mInterface.getNetData(1).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    String result = "";
                    try {
                        result = response.body().string().toString();
                        JSONObject object = new JSONObject(result);
                        JSONObject data = object.optJSONObject("data");
                        JSONArray strategy = data.optJSONArray("strategy");
                        for (int i = 0; i < strategy.length(); i++) {
                            JSONObject jsonObject = strategy.optJSONObject(i);
                            if (jsonObject.optString("stra_id").equals(getIntent().getStringExtra("stra_id"))) {
                                continue;
                            }
                            Goods goods = new Goods();
                            goods.collection_num = jsonObject.optString("collection_num");
                            goods.description = jsonObject.optString("description");
                            goods.image = jsonObject.optString("image");
                            goods.logo_image = jsonObject.optString("logo_image");
                            goods.market_time = jsonObject.optString("market_time");
                            goods.page_views = jsonObject.optString("page_views");
                            goods.refer_content = jsonObject.optString("refer_content");
                            goods.refer_type = jsonObject.optString("refer_type");
                            goods.share_content = jsonObject.optString("share_content");
                            goods.share_image = jsonObject.optString("share_image");
                            goods.share_title = jsonObject.optString("share_title");
                            goods.share_url = jsonObject.optString("share_url");
                            goods.stra_id = jsonObject.optString("stra_id");
                            goods.title = jsonObject.optString("title");
                            mListGoodsAll.add(goods);
                        }
                        for (int i = 0; i < 3; i++) {
                            mListGoods.add(mListGoodsAll.get(i));
                        }
                        mAdapterList.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        mDialog.dismiss();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("123", "这是为什么");
            }
        });
    }

    private void loadUser() {
        mInterface.getNetUser(Integer.parseInt(getIntent().getStringExtra("stra_id"))).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        String result = response.body().string().toString();
                        JSONObject object = new JSONObject(result);
                        JSONObject data = object.optJSONObject("data");
                        JSONArray array = data.optJSONArray("avatar");
                        if (array.length() <= 5) {
                            for (int i = 0; i < array.length(); i++) {
                                User user = new User();
                                JSONObject object1 = array.optJSONObject(i);
                                user.avatar = object1.optString("avatar");
                                user.name = object1.optString("name");
                                user.time = object1.optString("time");
                                mList.add(user);
                            }
                        } else {
                            for (int i = 0; i < 5; i++) {
                                User user = new User();
                                JSONObject object1 = array.optJSONObject(i);
                                user.avatar = object1.optString("avatar");
                                user.name = object1.optString("name");
                                user.time = object1.optString("time");
                                mList.add(user);
                            }
                        }
                        avatar_count = data.optInt("avatar_count");
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        initView();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                mDialog.dismiss();
            }
        });
    }

    private void loadViewForPullToZoomScrollView(PullToZoomScrollViewEx scrollView) {

        View headView = LayoutInflater.from(this).inflate(R.layout.head_view, null);
        LinearLayout linearLayout = (LinearLayout) headView.findViewById(R.id.ll_action_button);
        linearLayout.setBackgroundColor(Color.argb(50, 0, 0, 0));
        TextView mTextViewTitle = (TextView) headView.findViewById(R.id.tv_title);
        TextView mTextViewTime = (TextView) headView.findViewById(R.id.tv_time);
        mTextViewTitle.setText(getIntent().getStringExtra("title"));
        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.parseLong(getIntent().getStringExtra("time") + "000")));
        mTextViewTime.setText(time);
        View zoomView = LayoutInflater.from(this).inflate(R.layout.head_zoom_view, null);
        ImageView mImageView = (ImageView) zoomView.findViewById(R.id.imageView);
        Glide.with(this).load(getIntent().getStringExtra("icon")).into(mImageView);

        View contentView = LayoutInflater.from(this).inflate(R.layout.content_view, null);
        mTextViewMore = (TextView) contentView.findViewById(R.id.tv_user_more);
        if (avatar_count > 5) {
            mTextViewMore.setVisibility(View.VISIBLE);
        }
        mTextViewMore.setOnClickListener(this);
        TextView mTextView = (TextView) contentView.findViewById(R.id.tv_test1);
        mTextView.setText(avatar_count + "人收藏该攻略");
        RecyclerView mRecyclerView = (RecyclerView) contentView.findViewById(R.id.recyclerView);
        if (mList.size() != 0) {
            mAdapter = new MyRecycleViewAdapter(mList, this);
            if (mList.size() < 5) {
                manager = new GridLayoutManager(this, mList.size(), LinearLayoutManager.VERTICAL, false);
            } else {
                manager = new GridLayoutManager(this, 5, LinearLayoutManager.VERTICAL, false);
            }
            mRecyclerView.setLayoutManager(manager);
            mRecyclerView.setAdapter(mAdapter);
        }else {
            mTextView.setText("暂时还没有人收藏该攻略");
            mRecyclerView.setVisibility(View.GONE);
        }
        MyListView mListView = (MyListView) contentView.findViewById(R.id.lv_content_view);
        mAdapterList = new MyListViewAdapter(mListGoods, this);
        mListView.setAdapter(mAdapterList);
        mListView.setOnItemClickListener(this);

        scrollView.setHeaderView(headView);
        scrollView.setZoomView(zoomView);
        scrollView.setScrollContentView(contentView);
    }


    // 设置头部的View的宽高。
    private void setPullToZoomViewLayoutParams(PullToZoomScrollViewEx scrollView) {
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(localDisplayMetrics);
        int mScreenHeight = localDisplayMetrics.heightPixels;
        int mScreenWidth = localDisplayMetrics.widthPixels;
        LinearLayout.LayoutParams localObject = new LinearLayout.LayoutParams(mScreenWidth,
                (int) (9.0F * (mScreenWidth / 16.0F)));
        scrollView.setHeaderLayoutParams(localObject);
    }

    public void click(View view) {
        switch (view.getId()) {
            case R.id.tv_test4:
                Intent intent = new Intent(this, StrategyActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent(this, DetailsActivity.class);
        intent.putExtra("title", mListGoods.get(i).title);
        intent.putExtra("icon", mListGoods.get(i).image);
        intent.putExtra("time", mListGoods.get(i).market_time);
        intent.putExtra("stra_id", mListGoods.get(i).stra_id);
        startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_user_more:
                Intent intent = new Intent(this, UserActivity.class);
                intent.putExtra("stra_id", getIntent().getStringExtra("stra_id"));
                startActivity(intent);
                break;
            default:
                break;
        }
    }
}
